﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SampleImageGenerator.Core;
using SampleImageGenerator.Core.Events;

namespace SampleImageGenerator.Controls
{
	internal partial class Console : EngineListenerControl
	{
		public Console()
		{
			InitializeComponent();

			UpdateState(Engine); 
		}
		
		protected override void AttachEventHandlers(IEngine engine)
		{
			engine.BusyChanged += BusyChangedHandler;
			engine.ImageGenerated += ImageGeneratedInvoker;
		}
		
		protected override void DetachEventHandlers(IEngine engine)
		{
			engine.BusyChanged -= BusyChangedHandler;
			engine.ImageGenerated -= ImageGeneratedInvoker;
		}
		
		protected override void UpdateState(IEngine engine)
		{
			BusyGui(engine.Busy);
		}

		private void BusyGui(Boolean busy)
		{
			tbConsole.Enabled = !busy;
			btnGo.Enabled = !busy;
			btnCancel.Enabled = busy;
		}

		private void ImageGeneratedInvoker(object sender, ImageGeneratedEventArgs e)
		{
			if (this.InvokeRequired)
			{
				Object[] args = new Object[] { sender, e };
				EventHandler<ImageGeneratedEventArgs> handler = ImageGeneratedHandler;
				this.Invoke(handler, args);
			}
			else
			{
				ImageGeneratedHandler(sender, e);
			}
		}

		private void ImageGeneratedHandler(object sender, ImageGeneratedEventArgs e)
		{
			tbConsole.Text = e.Description;
		}

		private void BusyChangedHandler(object sender, EventArgs e)
		{
			if (this.InvokeRequired)
			{
				Object[] args = new Object[] { sender, e };
				EventHandler handler = BusyChangedHandler;
				this.Invoke(handler, args);
			}
			else
			{
				BusyGui(Engine.Busy); 
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			try
			{
				Engine.RequestCancellationAsync();
			}
			catch (Exception ex)
			{
				GuiUtilities.HandleException(ex); 
			}
		}

		private void btnGo_Click(object sender, EventArgs e)
		{
			try
			{
				String xml = tbConsole.Text;
				Engine.GenerateImageAsync(xml);
			}
			catch (Exception ex)
			{
				GuiUtilities.HandleException(ex); 
			}
		}
	}
}
